import java.util.Random;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 26727
 * Date: 2024-08-12
 * Time: 8:06
 */
class Solution4 {
    public int[] smallestK(int[] arr, int k) {
        qsort(arr,0,arr.length-1,k);

        int[] ret = new int[k];

        for(int i = 0; i < k; i++) {
            ret[i] = arr[i];
        }

        return ret;
    }

    public void qsort(int[] nums,int l, int r, int k) {

        if(l >= r) return;
        int key = nums[new Random().nextInt(r-l+1)+l];
        int left = l-1,right = r+1, i = l;


// 1.划分3块
        while(i < right) {
            if(nums[i] < key) {
                swap(nums,++left,i++);
            }else if(nums[i] == key) {
                i++;
            }else {
                swap(nums,--right,i);
            }
        }
// 2.判断
        int a = left - l + 1, b = right - left -1;
        if(a > k) {
            qsort(nums,l,left,k);
        }else if(a+b >= k) {
            return;
        }else {
            qsort(nums,right,r,k-a-b);
        }
    }

    public void swap(int[] nums,int i, int j) {
        int tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;
    }
}
